/**
 * AS2 by Grant Skinner
 */


package wiiless.utils
{
	
	import flash.filters.ColorMatrixFilter;
	
	public class ColorMatrix
	{
		private static var r_lum:Number = 0.212671;
		private static var g_lum:Number = 0.715160;
		private static var b_lum:Number = 0.072169;

		private static var IDENTITY:Array = new Array(1,0,0,0,0,
												  0,1,0,0,0,
												  0,0,1,0,0,
												  0,0,0,1,0);
		
		public var matrix:Array;
		
		function ColorMatrix ()
		{
				reset();
		}
		
		public function reset():void
		{
			matrix = IDENTITY.concat();
		}
		
		public function adjustSaturation ( s:Number ):void
		{
			var is_:Number=1-s;
			
		    var irlum:Number = is_ * r_lum;
			var iglum:Number = is_ * g_lum;
			var iblum:Number = is_ * b_lum;
			
			var mat:Array =  new Array (irlum + s, iglum    , iblum    , 0, 0,
						  			irlum    , iglum + s, iblum    , 0, 0,
						    		irlum    , iglum    , iblum + s, 0, 0,
						    		0        , 0        , 0        , 1, 0 );
		
			
			concat(mat);
		}

		public function concat(mat:Array):void
		{
			
			var temp:Array = new Array ();
			var i:Number = 0;
			
			for (var y:Number = 0; y < 4; y++ )
			{
				
				for (var x:Number = 0; x < 5; x++ )
				{
					temp[i + x] = mat[i    ] * matrix[x     ] + 
								   mat[i+1] * matrix[x +  5] + 
								   mat[i+2] * matrix[x + 10] + 
								   mat[i+3] * matrix[x + 15] +
								   (x == 4 ? mat[i+4] : 0);
				}
				i+=5;
			}
			
			matrix = temp;
			
		}
		
		public function get filter():ColorMatrixFilter
		{
			return new ColorMatrixFilter( matrix );
		}
	
		
	}
}
